<template>
  <div class="menu-page">
    <div id="userPage">
      <div class="userInfo">
        <!--  用户个人信息框    -->
        <el-descriptions border>
          <template #title>
            <el-avatar
                :src="user.GetHeadImg"
                size="large"
                style="margin: 20px;"
            />
          </template>
          <el-descriptions-item align="center">
            <template #label>
              <div>
                <el-icon>
                  <User/>
                </el-icon>
                姓名
              </div>
            </template>
            {{ info.user.name }}
          </el-descriptions-item>
          <el-descriptions-item align="center">
            <template #label>
              <div>
                <el-icon>
                  <Pointer/>
                </el-icon>
                性别
              </div>
            </template>
            {{ info.user.gender }}
          </el-descriptions-item>
          <el-descriptions-item align="center">
            <template #label>
              <div>
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
                邮箱
              </div>
            </template>
            {{ info.user.email }}
          </el-descriptions-item>
          <el-descriptions-item align="center">
            <template #label>
              <div>
                <el-icon>
                  <Iphone/>
                </el-icon>
                电话
              </div>
            </template>
            {{ info.user.phone }}
          </el-descriptions-item>
          <el-descriptions-item align="center">
            <template #label>
              <div>
                <el-icon>
                  <Timer/>
                </el-icon>
                出生
              </div>
            </template>
            {{ info.user.birth }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="info-setting">
        <el-tabs
            tab-position="left"
            style="height: 500px"
            class="demo-tabs"
            @tab-change="tabsChange"
            v-model="activeName"
        >
          <el-tab-pane name="用户设置" label="用户设置">
            <el-form
                ref="userFromRef"
                class="user-setting"
                :model="userInfoBack"
                :disabled="false"
                :rules="rules"
            >
              <div class="user-setting-image">
                <el-avatar
                    :src="user.GetHeadImg"
                />
                <el-button type="primary" size="small" text @click="uploadOpen">
                  更换
                </el-button>
              </div>
              <div class="user-setting-info">
                <el-form-item class="user-setting-item" label="账号">
                  <el-input disabled v-model="userInfoBack.account"/>
                </el-form-item>
                <el-form-item class="user-setting-item" label="姓名" prop="name">
                  <el-input v-model="userInfoBack.name"/>
                </el-form-item>
                <el-form-item class="user-setting-item" label="出生" prop="birth">
                  <el-date-picker v-model="userInfoBack.birth" value-format="YYYY-MM-DD hh:mm:ss"/>
                </el-form-item>
                <el-form-item class="user-setting-item" label="性别" prop="gender">
                  <el-radio-group v-model="userInfoBack.gender" size="small">
                    <el-radio-button label="男"/>
                    <el-radio-button label="女"/>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-form>
            <div v-show="infoUpdate">
              <el-button type="primary" @click="save(userFromRef)">
                保存
              </el-button>
              <el-button @click="cancel">
                取消
              </el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane  name="组织管理" label="组织管理">
            <div class="org-setting">
              <el-table :data="orgs">
                <el-table-column label="组织" width="500">
                  <template #default="scope">
                    {{ scope.row.name }}
                  </template>
                </el-table-column>
                <el-table-column label="默认角色">
                  <template #default="scope">
                    <!--   待完成修改组织默认角色     -->
                    <div class="role-box">
                      <el-select v-model="scope.row.now_role" @change="Change(scope.row.now_role,scope.row.orgId)"
                                 style="width: 100px;">
                        <el-option v-for="(role,index) in scope.row.roles"
                                   :key="index"
                                   :label="role.name"
                                   :value="role.role_id"
                        />
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" width="150">
                  <template #default="scope">

                    <div style="display: flex;flex-direction: row-reverse;justify-content: space-between">
                      <!-- 用户当前默认阻止不允许退出，当用户有且仅有一个组织时候只能通过管理员执行让其退出组织，具体操作查看组织管理删除用户操作   -->
                      <el-popconfirm
                        title="是否退出组织?"
                        @confirm="quit(scope.row)"
                        v-if="user.userInfo.user.orgId!=scope.row.orgId"
                      >
                        <template #reference>
                          <el-button link type="danger">
                            退出
                          </el-button>
                        </template>
                      </el-popconfirm>
                      <!--  当前默认组织不显示设置按钮 -->

                      <!--   待完成修改用户默认组织
                      user.userInfo.org!=scope.row.orgId 判断当前组织是否是默认组织
                      不是默认组织则显示按钮，可以修改为默认组织
                      -->
                      <el-button
                          @click="modifyDefaultOrg(scope.row.orgId,scope.row.now_role)"
                          link type="primary" v-if="user.userInfo.user.orgId!=scope.row.orgId">
                        default
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane name="账号安全" label="账号安全">
          </el-tab-pane>
        </el-tabs>
      </div>
      <!--   头像上传对话框   -->
      <el-dialog
          v-model="changHead"
          title="更换头像"
          append-to-body
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          :center="true"
          width="30%"
          draggable
          style="border-radius: 10px"
          :before-close="uploadClose"
      >
        <div style="width: 100%;display: flex;flex-direction: row;justify-content: center">
          <el-upload
              class="avatar-uploader"
              ref="headUploadRef"
              method="POST"
              :action="uploadUrl"
              :headers="uploadToken()"
              :data="uploadData"
              name="image"
              :auto-upload="false"
              :on-success="handleAvatarSuccess"
              :on-progress="Progress"
              :on-change="UploadChange"
              :on-remove="UploadRemove"
              :on-error="UploadError"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <template #footer>
          <el-button type="primary" @click="SaveUpload" :loading="saveLoad">保存</el-button>
          <el-button @click="CloseUploadButton">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, onUnmounted, onUpdated, reactive, ref, watch} from "vue";

import {userStore} from "../../../store/user";
import Axios from "../../../plugins/axios";
import {type} from "../../../model/type";
import {
  ElMessage,
  FormInstance,
  FormRules,
  UploadFile,
  UploadFiles,
  UploadProgressEvent,
  UploadProps
} from "element-plus";
import {sys} from "../../../model/system";
import event from "../../../plugins/event";
import {QuitOrg, UpdateUserInfo} from "../../../plugins/evenKey";

const user = userStore()

// 存放用户信息
const info = ref()
// 存放编辑用户信息备份
const userInfoBack = ref()
const infoUpdate = ref(false)

const orgs = ref<any>([])

const changHead = ref(false)
const imageUrl = ref('')

const headUploadRef = ref()


info.value = user.userInfo

// userInfoBack.value = {...info.value.user}
userInfoBack.value = {...info.value.user}


// 监听用户信息变更
watch(userInfoBack,
    (newValue, oldValue) => {
      // 用户修改了信息 通过infoUpdate去显示对应操作 保存或是重置
      infoUpdate.value = !equal(userInfoBack.value, info.value.user)
    }, {deep: true})

// 判断属性值是否相等
function equal(obj1: type.User, obj2: type.User): boolean {
  if (obj1.name !== obj2.name) {
    return false
  }
  if (obj1.gender !== obj2.gender) {
    return false
  }
  if (obj1.birth !== obj2.birth) {
    return false
  }
  return true
}

function save(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate((valid)=>{
    if (valid){
      Axios.post('/api/user/setting/info',userInfoBack.value).then(
          response=>{
            let data:sys.Result<any> =response.data
            if (data.code==='0000'){
              ElMessage({
                type:'success',
                message:data.msg
              })
              event.emit(UpdateUserInfo)
            }
          }
      )
    }else {
      ElMessage({
        type:'warning',
        message:'检查信息'
      })
    }
  })
}

function cancel() {
  userInfoBack.value = {...info.value.user}
}


function uploadOpen() {
  changHead.value = true
  saveLoad.value = false
  imageUrl.value = ''
  // 清空上传列表
}

function uploadClose() {
  headUploadRef.value.clearFiles()
  changHead.value = false
}

function CloseUploadButton() {
  changHead.value = false
  headUploadRef.value.clearFiles()
}

const saveLoad = ref(false)
const uploadUrl = ref('http://localhost:2024/api/user/setting/header')

function SaveUpload() {
  saveLoad.value = true
  headUploadRef.value.submit()
}

function uploadToken(): Record<string, any> {
  return {
    Authorization: 'Bearer ' + user.userInfo.token
  }
}

function uploadData(): any {
  return {
    image: user.userInfo.user.picture
  }
}

// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  if (response.code == "0000") {
    ElMessage({
      duration: 2000,
      message: response.msg,
      type: 'success'
    })
    user.userInfo.user.picture = response.data
    user.UpdateToken(user.userInfo)
  }
  uploadClose()
}

const Progress: UploadProps['onProgress'] = (evt: UploadProgressEvent, uploadFile: UploadFile, uploadFiles: UploadFiles) => {

}


const UploadError: UploadProps['onError'] = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  ElMessage({
    duration: 2000,
    message: '上传失败',
    type: 'error'
  })
}

// 选择上传的头衔触发，修改页面显示
const UploadChange: UploadProps["onChange"] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

// 删除文件
const UploadRemove: UploadProps["onRemove"] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('remove')
  imageUrl.value = ''
}

// 组织默认默认角色下拉框修改变更
function Change(role, org) {
  Axios.post('/api/user/role/default', {
    role: role,
    org: org
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      user.userInfo.orgs = data.data.orgs
      user.userInfo.roles = data.data.roles
      user.UpdateToken(user.userInfo)
      ElMessage({
        type: 'success',
        message: '组织默认角色修改成功',
        duration: 1000
      })
    }
  })
}

// 需改默认组织和对应的默认角色
function modifyDefaultOrg(orgId: number, role: number) {
  console.log("orgId:", orgId, "role:", role)
  Axios.post('/api/user/org/default', {
    role: role,
    org: orgId
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      if (data.data === true) {
        // 表示修改成功 会写当前角色的默认组织信息
        ElMessage({
          type: 'success',
          message: '默认组织修改成功',
          duration: 1000
        })
        event.emit(UpdateUserInfo)
      }
    }
  })
}

// 执行退出组织
function quit(row) {
  Axios.post('/api/user/quit/org',{
    userId:user.userInfo.user.id,
    orgId:row.orgId
  }).then(response=>{
    let data:sys.Result<any> =response.data
    if (data.code==='0000'){
        // 更新当前用户的组织和角色信息
        event.emit(UpdateUserInfo)
    }
  })
}

const activeName=ref(user.center.activeName)

function tabsChange(TabPaneName: string) {
  user.SetActiveName(TabPaneName)
}


const userFromRef = ref<FormInstance>()

const userName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('昵称不能为空'))
  } else {
    callback()
  }
}

const birthName = (rule: any, value: any, callback: any) => {
  if (value === null) {
    callback(new Error('生日不能为空'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  name: [{ validator: userName, trigger: 'blur' }],
  birth:[{validator: birthName, trigger: 'blur'}],
})


function init() {
  orgs.value=[]
  info.value = user.userInfo
  userInfoBack.value = {...info.value.user}
  user.userInfo.orgs.forEach(org => {
    // 初始化组织管理展示的组织角色信息
    org.roles = []
    // 当前组织默认用户信息
    org.now_role = ''
    user.userInfo.roles.forEach(role => {
      if (org.orgId == role.org_id) {
        org.roles.push(role)
      }
      // 查询 当前组织的默认角色
      Axios.get("/api/default/our", {
        params: {
          org: org.orgId
        }
      }).then(response => {
        let data = response.data
        if (data.code === "0000") {
          org.now_role = data.data
        }
      })
    })
    orgs.value.push(org)
  })
}


onMounted(init)
event.on(QuitOrg,init)
onUnmounted(()=>{
  event.off(QuitOrg,init)
})
</script>

<style scoped>
#userPage {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.userInfo,.info-setting {
  width: 97%;
  margin: auto;
  box-shadow: var(--el-box-shadow-lighter);
  background-color: white;
}



.user-setting {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  margin-top: 10px;
}

.user-setting-info {
  width: 200px;
}

.user-setting-item {
  margin-top: 10px;
}

.role-box {
  display: flex;
  flex-direction: row;
  margin-right: auto;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>